<?php
/**
 * Created by PhpStorm.
 * User: tommy
 * Date: 2018/6/13
 * Time: 16:30
 */

namespace frontend\service;


use common\component\Constant;
use common\component\TagRelationRedisImp;
use common\event\SubscriptionEvent;
use common\models\info\Tags;
use common\models\info\TagsRelation;
use common\models\messager\Notify;
use common\utils\CommonUtil;
use frontend\component\ResultFormat;

class TagService
{
    /**
     * 话题 首页数据
     */
    public static function tagIndexData() {
        $result = [
            "hot"=>[],
            "order"=>[]
        ];
        $data = Tags::getCacheAllTags();
        if (count($data)) {
            foreach ($data as $item) {
                $item['url'] = CommonUtil::generateUrl($item['id'],Constant::ROUTE_TAG);
                if ($item['is_rec']) {
                    $result["hot"][] = $item;
                }
                $result["order"][$item['first_letter']][] = $item;
            }
        }
        return $result;
    }

    public static function tagIndexDataByUid($uid) {
        $key = "Tag:by:uid:".$uid;
        $result = CommonUtil::getCache(__CLASS__,$key);
        if(!count($result['hot'])&&!count($result['order'])) {
            $result = [
                "hot"=>[],
                "order"=>[]
            ];
            $tag_arr = static::getTagIdsByUid($uid,1,1000);
            $data = Tags::getTagArr($tag_arr);
            if (count($data)) {
                foreach ($data as $item) {
                    $item['first_letter'] = strtoupper($item['first_letter']);
                    $item['url'] = CommonUtil::generateUrl($item['id'],Constant::ROUTE_TAG);
                    if ($item['is_rec']) {
                        $result["hot"][] = $item;
                    }
                    $result["order"][$item['first_letter']][] = $item;
                }
                CommonUtil::setCache(__CLASS__,$key,$result,600);
            }
        }
        return $result;
    }

    /*
     * 话题详情数据
     */
    public static function tagDetailByName($tag_name) {
        $data = Tags::loadRowDataByName($tag_name);
        return $data;
    }

    /*
     * 话题详情数据
     */
    public static function tagDetailById($tag_id) {
        $data = Tags::loadRowDataById($tag_id);
        return $data;
    }

    /**
     * 异步调用
     * 订阅用户总数,关联文章总数,文章列表
     * @param $tag_id
     * @param $user_id
     * @return string
     */
    public static function asyncTotalData($tag_id,$user_id = 0) {
        $result = [
            "follow_total" => 0,
            "article_total" => 0,
            "is_follow" => false,
            "user_id" => $user_id
        ];
        $result["article_total"] = (int)Tags::getFieldById($tag_id,"article_total");
        $obj = new TagRelationRedisImp($tag_id,$user_id);
        $result["follow_total"] = (int)$obj->getUserCount();
        $result["is_follow"] = (int)$obj->isSubscribe();
        return ResultFormat::success("获取成功",$result);
    }

    /**
     * 获取标签(话题)下对应的文章
     * @param $tag_id
     * @param $page
     * @param $pageSize
     * @return string
     */
    public static function getArticleListByTagId($tag_id,$page,$pageSize) {
        $result = TagsRelation::getArticleByTagId($tag_id,$page,$pageSize);
        return ResultFormat::success("获取成功",$result);
    }


    public static function subscribe($tag_id,$user_id) {
        $obj = new TagRelationRedisImp($tag_id,$user_id);
        $obj->on(TagRelationRedisImp::EVENT_BEFORE_SUBSCRIBE,["common\component\EventService","beforeSubscribe"]);
        $obj->on(TagRelationRedisImp::EVENT_AFTER_SUBSCRIBE,["common\component\EventService","afterSubscribe"]);
        if (!$obj->subscribe()) {
            return ResultFormat::error($obj->getErrorString());
        }
        return ResultFormat::success("操作成功",["sub_total"=>$obj->getUserCount()]);
    }

    public static function cancelTag($tag_id,$user_id) {
        $obj = new TagRelationRedisImp($tag_id,$user_id);
        $obj->on(TagRelationRedisImp::EVENT_AFTER_CANCEL,["common\component\EventService","afterCancelSubscribe"]);
        $result = $obj->deSubscribe();
        if (!$result) {
            return ResultFormat::error($obj->getErrorString());
        }
        return ResultFormat::success("操作成功",["sub_total"=>$obj->getUserCount()]);

    }

    /**
     * 获取用户订阅的话题
     * @param $user_id
     * @param int $page
     * @param int $pageSize
     * @return array|string
     */
    public static function getTagsByUid($user_id,$page=1,$pageSize=20) {
        $obj = new TagRelationRedisImp(0,$user_id);
        $tag_ids = $obj->getTagList($page,$pageSize);
        $result = [];
        if ($tag_ids) {
            foreach ($tag_ids as $tag_id) {
                $result[] = [
                    'id'=> (int)$tag_id,
                    'title' => Tags::getFieldById($tag_id),
                    'link' => CommonUtil::generateUrl($tag_id,Constant::ROUTE_TAG),
                ];
            }
        }
        return ResultFormat::success("获取成功",$result);
    }

    public static function getBaseTagsByUid($user_id) {
        $obj = new TagRelationRedisImp(0,$user_id);
        $tag_ids = $obj->getTagList(1,100);
        $rec_tag = Tags::arrIndexHotTag(Tags::REC_RECOMMEND);

        if ($rec_tag["rows"]) {
            foreach ($rec_tag["rows"] as $key => $row) {
                if (in_array($row["id"],$tag_ids)) {
                    $rec_tag["rows"][$key]["selected"] = 1;
                } else {
                    $rec_tag["rows"][$key]["selected"] = 0;
                }
            }
        }
        $result = [];
        if ($tag_ids) {
            foreach ($tag_ids as $tag_id) {
                $result[] = [
                    'id'=> (int)$tag_id,
                    'link'=> CommonUtil::generateUrl((int)$tag_id,Constant::ROUTE_TAG),
                    'title' => Tags::getFieldById($tag_id),
                ];
            }
        }
        return [
            "current" => $result,
            "recommend" => $rec_tag["rows"]
        ];
    }

    public static function getBaseTagsByUidNew($user_id) {
        $obj = new TagRelationRedisImp(0,$user_id);
        $tag_ids = $obj->getTagList(1,100);
        $rec_tag = Tags::arrIndexHotTag(Tags::REC_RECOMMEND);

        if ($rec_tag["rows"]) {
            foreach ($rec_tag["rows"] as $key => $row) {
                if (in_array($row["id"],$tag_ids)) {
                    $rec_tag["rows"][$key]["selected"] = 1;
                } else {
                    $rec_tag["rows"][$key]["selected"] = 0;
                }
            }
        }
        $result = [];
        if ($tag_ids) {
            foreach ($tag_ids as $tag_id) {
                $tag_name = Tags::getFieldById($tag_id);
                if($tag_name) {
                    $result[] = [
                        'id'=> (int)$tag_id,
                        'link'=> CommonUtil::generateUrl((int)$tag_id,Constant::ROUTE_TAG),
                        'title' => $tag_name,
                    ];
                }
            }
        }
        return ResultFormat::success("操作成功",[
            "current" => $result,
            "recommend" => $rec_tag["rows"]
        ]);
    }


    public static function getTagIdsByUid($user_id,$page=1,$pageSize=20) {
        $data = self::getTagsByUid($user_id,$page,$pageSize);
        $data = json_decode($data,true);
        $result = [];
        if (count($data['data'])) {
            foreach ($data["data"] as $item) {
                $result[] = $item['id'];
            }
        }
        return $result;
    }

    /**
     * @param $aid
     * @return array|mixed ['id'=>1,'text'=>'标签名']
     */
    public static function getTagsByArticle($aid) {
        $tags = TagsRelation::getTagInfoByArtId($aid);
        return $tags;
    }

    public static function getRecommendTags($is_rec = Tags::REC_RECOMMEND,$page=1,$pageSize=9) {
        $tags = Tags::arrIndexHotTag($is_rec,$page,$pageSize);
        return $tags;
    }

    /*
     * 检查用户是否已关注
     */
    public static function isSubscribe($tag_id,$user_id) {
        $obj = new TagRelationRedisImp($tag_id,$user_id);
        return $obj->isSubscribe() ? 1 :0;
    }
}
